package com.xuan.bigdog.lib.tabframe.mcall;

import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TabHost.TabSpec;

import com.xuan.bigappleui.lib.utils.ui.M;
import com.xuan.bigdog.R;

/**
 * 框架主界面
 * 
 * @author xuan
 * @version $Revision: 1.0 $, $Date: 2013-10-25 下午6:55:29 $
 */
public class DGFrameActivity extends CallFragmentActivity implements
		CallByFragmentListener {
	protected FragmentTabHost tabhost;

	protected RadioGroup tab;

	/** 下面tab按钮数组 */
	protected RadioButton[] tabBtns;

	/**
	 * 主界面所需要管理的Fragment片段
	 */
	private Class<?>[] fragments;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dg_tabframe_mcall_frame);
		fragments = initFragment();
		initWidgets();
	}

	// Init view
	private void initWidgets() {
		tabhost = (FragmentTabHost) findViewById(M.id(this, "tabhost"));
		tab = (RadioGroup) findViewById(M.id(this, "tab"));
		tabBtns = new RadioButton[4];
		tabBtns[0] = (RadioButton) findViewById(M.id(this, "tabbtn1"));
		tabBtns[1] = (RadioButton) findViewById(M.id(this, "tabbtn2"));
		tabBtns[2] = (RadioButton) findViewById(M.id(this, "tabbtn3"));
		tabBtns[3] = (RadioButton) findViewById(M.id(this, "tabbtn4"));

		tabhost.setup(this, getSupportFragmentManager(),
				M.id(this, "realtabcontent"));

		// 设置子界面
		for (int i = 0, n = fragments.length; i < n; i++) {
			TabSpec tabSpec = tabhost.newTabSpec(String.valueOf(i))
					.setIndicator(String.valueOf(i));
			tabhost.addTab(tabSpec, fragments[i], null);
		}

		tab.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == M.id(DGFrameActivity.this, "tabbtn1")) {
					tabhost.setCurrentTab(0);
				} else if (checkedId == M.id(DGFrameActivity.this, "tabbtn2")) {
					tabhost.setCurrentTab(1);
				} else if (checkedId == M.id(DGFrameActivity.this, "tabbtn3")) {
					tabhost.setCurrentTab(2);
				} else if (checkedId == M.id(DGFrameActivity.this, "tabbtn4")) {
					tabhost.setCurrentTab(3);
				}
			}
		});

		// 默认选中第一个
		tabBtns[0].setChecked(true);
	}

	/**
	 * 设置选中某个tab页面
	 * 
	 * @param index
	 */
	public void setTab(int index) {
		index = Math.min(Math.max(index, (tabBtns.length - 1)), 0);
		tabhost.setCurrentTab(index);
	}

	/**
	 * 子类自己实现Fragment
	 * 
	 * @param fragments
	 */
	protected Class<?>[] initFragment() {
		return new Class<?>[] { DGFrameFragment.class, DGFrameFragment.class,
				DGFrameFragment.class, DGFrameFragment.class };
	}

}
